<template>
  <!-- 隐藏的离屏Canvas，用于拍照后的处理 -->
  <canvas style="width:600rpx;height:500rpx;position:fixed;top:-9999px; border-radius: 40rpx;"
    canvas-id="photo-processor">
  </canvas>

  <view class="container">
    <!-- 相机组件 -->
    <view>
      <camera v-if="showCamera" :device-position="deviceType" :flash="flashMode" class="camera-view"
        :style="currentFilter.style">
      </camera>
    </view>

    <!-- 倒计时显示 -->
    <view v-if="countdown.value > 0" class="countdown-box">
      <text class="countdown-text">{{ formatTime(countdown.value) }}</text>
    </view>

    <!-- 功能操作区 -->
    <view class="panel">
      <!-- 滤镜选择 -->
      <scroll-view scroll-x class="filter-scroll" :scroll-left="scrollLeft" :scroll-with-animation="true">
        <view v-for="(filter, index) in filters" :key="index" :id="`item-${index}`"
          :class="['filter-item', currentFilterIndex === index ? 'active' : '']" @tap="selectFilter(index)">
          {{ filter.name }}
        </view>
      </scroll-view>

      <!-- 拍照按钮 -->
      <view class="camera-actions">
        <view class="action-btn" @tap="switchCamera">
          <text class="iconfont icon-xiangjifanzhuan"></text>
        </view>
        <view class="camera-btn" @tap="takePhoto"></view>
        <view class="action-btn" @tap="toggleFlash">
          <text class="iconfont"
            :class="[flashMode === 'on' ? 'icon-iconshanguangdeng' : 'icon-jinyongshanguangdeng']"></text>
        </view>
      </view>

      <!-- 定时拍照选项 -->
      <view class="timer-options">
        <view v-for="time in timerOptions" :key="time" :class="['timer-option', selectedTimer === time ? 'active' : '']"
          @tap="selectTimer(time)">
          {{ time }}s
        </view>
      </view>
    </view>

    <!-- 照片预览区 -->
    <view class="photo-preview">
      <!-- <view v-for="(photo, index) in state.photos" :key="index" class="photo-item" @tap="previewPhoto(photo)">
        <image v-if="photo" :src="photo" mode="aspectFill"></image>
      </view> -->
      <view v-for="(photo, index) in state.photos" :key="index" class="photo-item">
        <image v-if="photo" :src="photo" mode="aspectFill"></image>
        <!-- <view class="no-img" v-else><up-icon name="photo-fill" size="28"></up-icon></view> -->
      </view>
    </view>
  </view>
</template>

<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref, reactive, computed, nextTick } from 'vue';
import {
  applySepia,
  applyGrayscale,
  applyCoolTone,
  applyWarmSunlight,
  applyFreshFilter
} from './tool/newFilter';
import { usePhotoCapture } from './tool/useTakePhoto'

// 响应式状态
const showCamera = ref(true);
const deviceType = ref('front');
const flashMode = ref('off');
const currentFilterIndex = ref(0);
const selectedTimer = ref(3);
const typeParam = ref(null);
const scrollLeft = ref(0)
const state = reactive({
  photos: []
  // photos: Array(4).fill(null)
})
// 滤镜定义 - 修复CSS滤镜与JS滤镜效果一致
const filters = ref([
  {
    name: '原图',
    style: '',
    apply: null
  },
  {
    name: '棕褐色',
    style: 'filter: sepia(100%) hue-rotate(-18deg) saturate(1.3) brightness(1.0) contrast(1.05) opacity(0.95)',
    apply: applySepia
  },
  {
    name: '黑白',
    style: 'filter: grayscale(100%);',
    apply: applyGrayscale
  },
  // {
  //   name: '冷调',
  //   style: 'filter:brightness(1.1) contrast(1.25) saturate(0.7) hue-rotate(10deg) sepia(0.3) brightness(0.95);',
  //   apply: applyCoolTone
  // },
  {
    name: '暖阳',
    style: 'filter: sepia(30%) brightness(1.05) saturate(1.2) hue-rotate(-10deg);',
    apply: applyWarmSunlight
  },
  {
    name: '小清新',
    style: 'filter: brightness(1.1) contrast(0.95) saturate(1.2) hue-rotate(15deg);',
    apply: applyFreshFilter
  }
]);

// 计算属性
const currentFilter = computed(() => filters.value[currentFilterIndex.value]);
// const countdown = computed(() => camera.countdown || 0)

const timerOptions = [0, 3, 5, 10];

onLoad((options) => {
  if (options?.type) {
    typeParam.value = decodeURIComponent(options.type)
  }
})
onShow(() => {
  state.photos = []
})
// 倒计时补零方法
const formatTime = (seconds) => {
  return seconds.toString().padStart(2, '0');
};
//切换滤镜
const selectFilter = (index) => {
  currentFilterIndex.value = index;
  nextTick(() => {
    // 直接使用uni.createSelectorQuery()，不传入组件实例
    const query = uni.createSelectorQuery();
    query.select(`#item-${index}`).boundingClientRect();
    query.select('.filter-scroll').scrollOffset();
    query.select('.filter-scroll').boundingClientRect();
    query.exec((res) => {
      const itemData = res[0];
      const scrollData = res[1];
      const scrollViewRect = res[2];
      
      if (itemData && scrollData && scrollViewRect) {
        // 计算 scroll-view 的最大滚动距离
        const maxScrollLeft = scrollData.scrollWidth - scrollViewRect.width;
        
        // 计算当前项相对于滚动内容左边缘的位置
        const itemPosition = itemData.left - scrollViewRect.left + scrollData.scrollLeft;
        
        // 计算目标滚动位置：将当前项居中显示
        const targetScrollLeft = itemPosition - (scrollViewRect.width / 2) + (itemData.width / 2);
        
        // 确保滚动位置在有效范围内 [0, maxScrollLeft]
        scrollLeft.value = Math.max(0, Math.min(targetScrollLeft, maxScrollLeft));
      }
    });
  });
};


//前后摄像头切换
const switchCamera = () => {
  uni.vibrateShort({ type: 'medium' });
  deviceType.value = deviceType.value === 'back' ? 'front' : 'back';
};
//闪光灯
const toggleFlash = () => {
  uni.vibrateShort({ type: 'medium' });
  flashMode.value = flashMode.value === 'on' ? 'off' : 'on';
};
//设置倒计时
const selectTimer = (time) => {
  uni.vibrateShort({ type: 'medium' });
  selectedTimer.value = time;
  camera.setSeconds(selectedTimer.value)
};

//拍照
const capturePhoto = async () => {
  try {
    // 拍照
    const res = await uni.createCameraContext().takePhoto({
      quality: 'high'
    });

    // 应用滤镜
    const tempImagePath = res.tempImagePath;
    const processedImage = await applyFilter(tempImagePath);

    // 保存照片
    state.photos[camera.captureCount.value] = processedImage
  } catch (err) {
    console.error('拍照失败:', err);
    uni.showToast({
      title: '拍照失败',
      icon: 'none'
    });
  }
};
// 创建拍照控制器
const camera = usePhotoCapture(capturePhoto, {
  defaultCount: 4,
  defaultInterval: 1500, //等待下一次倒计时间隔时间
  countdownSeconds: selectedTimer.value// 设置默认倒计时秒数
})
const countdown = computed(() => camera.countdown || 0)

const takePhoto = async () => {
  // selectedTimer.value > 0 ? startCountdown() :  capturePhoto();
  await camera.captureContinuous(4, 1500)
  if (camera.captureCount.value >= 3) {
    getApp().globalData && (getApp().globalData.photos = state.photos)
    uni.navigateTo({ url: `/pages/preview/index?type=${typeParam.value}` })
  }
};
//使用滤镜
const applyFilter = async (imagePath) => {
  try {
    const canvasWidth = uni.upx2px(600)
    const canvasHeight = uni.upx2px(500)
    const ctx = uni.createCanvasContext('photo-processor');
    // 阶段1: 绘制基础图像
    await new Promise(resolve => {
      uni.getImageInfo({
        src: imagePath,
        success: (res) => {
          ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight);
          ctx.draw(true, resolve);
        }
      });
    });

    // 阶段2: 应用滤镜
    if (currentFilter.value.apply) {
      currentFilter.value.apply('photo-processor', canvasWidth, canvasHeight);
      await new Promise(resolve => ctx.draw(true, resolve));
    }

    // 阶段3: 生成最终图片
    return new Promise(resolve => {
      uni.canvasToTempFilePath({
        canvasId: 'photo-processor',
        quality: 0.95,
        destWidth: canvasWidth * 2,
        destHeight: canvasHeight * 2,
        success: (res) => {
          resolve(res.tempFilePath);
          ctx.clearRect(0, 0, canvasWidth, canvasHeight);
        },
        fail: () => resolve(imagePath)
      });
    });
  } catch (err) {
    console.error('滤镜处理失败:', err);
    return imagePath; // 出错时返回原图
  }
};
// 预览
const previewPhoto = (photoPath) => {
  uni.previewImage({
    urls: [photoPath],
    current: photoPath
  });
};
</script>

<style>
@import '@/static/font/iconfont.css';

page {
  overflow: hidden;
}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.camera-view {
  /* width: 100%;
  height: 70vh;
  position: relative; */
  margin-top: 40rpx;
  width: 600rpx;
  height: 500rpx;
  position: relative;
  border-radius: 40rpx;
  transition: filter 0.3s ease-in-out;
}

.countdown-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.countdown-text {
  font-size: 120rpx;
  color: #fff;
  font-weight: bold;
}

.panel {
  position: fixed;
  bottom: 0;
  height: 30vh;
  width: 100%;
  background: radial-gradient(black, transparent);
  box-sizing: border-box;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.filter-scroll {
  white-space: nowrap;
  width: 100%;
  height: 80rpx;
}

.filter-item {
  display: inline-block;
  padding: 10rpx 30rpx;
  margin-right: 20rpx;
  /* background: #333; */
  /* color: #fff; */
  color: #000;
  border-radius: 30rpx;
  font-size: 28rpx;
}

.filter-item.active {
  /* background: #07c160; */
  background: #333;
  color: #fff;
}

.camera-actions {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 120rpx;
}

.action-btn {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
}

.camera-btn {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: #fff;
  border: 8rpx solid rgba(255, 255, 255, 0.5);
}

.iconfont {
  font-size: 50rpx;
  color: #fff;
}

.timer-options {
  display: flex;
  justify-content: center;
}

.timer-option {
  width: 60rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  margin: 0 15rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  color: #000;
  font-size: 24rpx;
}

.timer-option.active {
  background: #333;
  color: #fff;
}

.photo-preview {
  position: absolute;
  bottom: 30vh;
  left: 0;
  right: 0;
  height: 220rpx;
  /* justify-content: center; */
  gap: 10rpx;
  align-items: center;
  display: flex;
  padding: 0 20rpx;
  overflow-x: auto;
  white-space: nowrap;
}

.photo-item {
  width: 150rpx;
  height: 150rpx;
  margin-right: 15rpx;
  border-radius: 10rpx;
  overflow: hidden;
  border: 2rpx solid #fff;
}

.photo-item image {
  width: 100%;
  height: 100%;
}

.photo-item .no-img {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}
</style>
